import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import viteCompression from 'vite-plugin-compression'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'
import eslintPlugin from 'vite-plugin-eslint'
import { ConfigEnv, loadEnv, UserConfig } from 'vite'
import { wrapperEnv } from './build/utils'
const pathResolve = (dir: string) => {
  return resolve(process.cwd(), '.', dir)
}
// https://vitejs.dev/config/
// const viteEnv = wrapperEnv(env);

export default defineConfig(({ command, mode }) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const viteEnv = wrapperEnv(env)
  return {
    root,
    base: viteEnv.VITE_PUBLIC_PATH,
    plugins: [vue(), viteCompression(), ViteImageOptimizer()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'), // 兼容src目录下的文件夹可通过 @/components/HelloWorld.vue写法
      },
    },
    css: {
      preprocessorMaxWorkers: true,
      preprocessorOptions: {
        scss: {
          additionalData: ['@import "./src/style/base.scss";'], // 全局公共样式
          charset: false,
        },
      },
    },
    build: {
      /** 构建后是否生成 source map 文件 */
      sourcemap: false,
      /** 是否在构建阶段将 publicDir 目录中的所有文件复制到 outDir 目录中 */
      copyPublicDir: true,
      /** 指定使用哪种混淆器。默认为 esbuild，它比 terser 快 20-40 倍，压缩率只差 1%-2% */
      minify: 'esbuild',
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
          manualChunks(chunk) {
            if (chunk.includes('node_modules')) return 'vendor'
          },
        },
      },
    },
    esbuild: {
      drop: viteEnv.VITE_DROP_CONSOLE ? ['console', 'debugger'] : [],
    },
  }
})
